package echat.future.cn.echat.video;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import echat.future.cn.echat.R;
import echat.future.cn.echat.my.utils.UserHelper;
import echat.future.cn.echat.video.domain.VideoData;
import lumingweihua.future.cn.baselibgxh.adapter.BaseViewHolder;
import lumingweihua.future.cn.baselibgxh.adapter.CommonAdapter;
import lumingweihua.future.cn.baselibgxh.base.BaseFragment;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialog;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialogEntity;
import lumingweihua.future.cn.baselibgxh.network.JsonElementRequest;
import lumingweihua.future.cn.baselibgxh.network.PureListRequest;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.CommonUtils;
import lumingweihua.future.cn.baselibgxh.utils.ImageUtils;

/**
 * Created by Administrator on 2018/9/21.
 */

public class FocusFragment extends BaseFragment {
    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_focus, container, false);
    }

    private CommonAdapter<VideoData> adapter;
    private List<VideoData> videoDatas;
    @Override
    protected void initData(Bundle savedInstanceState) {
        videoDatas = new ArrayList<>();
        adapter = new CommonAdapter<VideoData>(context,videoDatas,R.layout.item_focus) {
            @Override
            public void convert(BaseViewHolder holder, VideoData itemData, int position, ViewGroup parent) {
                holder.setImageByUrl(R.id.iv_img,itemData.getImg(), ImageUtils.imgOptionsSmall);
//                holder.setImageByUrl(R.id.iv_head,itemData.getAvatar(), ImageUtils.imgOptionsSmall);
//                holder.setText(R.id.tv_name,itemData.getUsername());
//                holder.setText(R.id.tv_tag,itemData.getSign());
                holder.setText(R.id.tv_gift,itemData.getGift_num());
                TextView tv_like = holder.getView(R.id.tv_like);
                tv_like.setText(itemData.getColletion_num()+"");
                if(itemData.getIs_collection())
                    tv_like.setCompoundDrawables(
                            CommonUtils.GetDrawable(context, R.drawable.shiping_zhanshi), null,
                            null, null);
                else
                    tv_like.setCompoundDrawables(
                            CommonUtils.GetDrawable(context, R.drawable.shiping_zhanshikong), null,
                            null, null);
                addClickListener(tv_like,position);

            }

            @Override
            public void processClick(int viewId, VideoData itemData) {
                super.processClick(viewId, itemData);
                switch (viewId) {
                    case R.id.tv_like:
                        FocusFragment.this.itemData = itemData;
                        requestCollect(!itemData.getIs_collection(),itemData.getId());
                        break;

                    default:
                        break;
                }
            }
        };
        GridView gridview = (GridView) findView(R.id.gridview);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                VideoData vd = videoDatas.get(position);
                int vid = 0;
                try {
                    vid = Integer.valueOf(vd.getId());
                } catch (Exception e) {
                    // TODO: handle exception
                }
                startActivity(new Intent(context,MyVideoActivity.class).putExtra("vid",vid));
//                if(vd.getCan_see())
//                    startActivity(new Intent(context,PlayVideoActivity.class)
//                            .putExtra("title",vd.getUsername())
//                            .putExtra("image",vd.getImg())
//                            .putExtra("url",vd.getVideo()));
//                else{
//                    currentPos = position;
//                    payVideo(vd.getVideo_price());
//                }
            }
        });
        requestGoodsDatas();

        rl_pay = findView(R.id.rl_pay);
        view_mask = findView(R.id.view_mask);
        view_mask.setOnClickListener(this);
        findView(R.id.bt_pay).setOnClickListener(this);
    }

    private View rl_pay;
    private View view_mask;
    private void payVideo(String price){

        new YesOrNoDialog(context, new YesOrNoDialogEntity("该视频需付费观看\n您确认付费麽?", "取消", "立即付费"), new YesOrNoDialog.OnYesOrNoDialogClickListener() {
            @Override
            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                switch (yesOrNoType) {
                    case BtnOk:
                        view_mask.setVisibility(View.VISIBLE);
                        rl_pay.setVisibility(View.VISIBLE);
                        setText(R.id.tv_coin,"E币："+price);
                        break;

                    default:
                        break;
                }
            }
        }).show();
    }

    VideoData itemData;

    private final int REQUEST_DATAS = 6;
    private final int REQUEST_COLLECT = 2;
    private final int REQUEST_CANCEL_COLLECT = 4;
    private final int REQUEST_PAY = 9;
    public boolean isNew;
    public boolean isFocus;

    public void requestGoodsDatas() {
        // TODO Auto-generated method stub
        baseActivity.showProgressBar(this);
        PureListRequest<VideoData, MamaHaoServerError> req = new PureListRequest<>(
                context,
                "/api/tab_video",
                this,
                VideoData.class);

        req.setParam("token", UserHelper.getToken());
        if(isFocus)
            req.setParam("type", "focus");
        if(isNew){
            req.setParam("type", "new");
//            if(!TextUtils.isEmpty(MyApplication.getInstance().getCity()) && MyApplication.getInstance().getCity().endsWith("市"))
//                req.setParam("city", MyApplication.getInstance().getCity().substring(0,MyApplication.getInstance().getCity().length()-1));
//            else
//                req.setParam("city", MyApplication.getInstance().getCity());

        }
        baseActivity.addRequestQueue(req, REQUEST_DATAS, new ReqTag.Builder().handleSimpleRes(true));

    }

    /**
     * 收藏
     */
    private void requestCollect(boolean isCollect,String id) {
        baseActivity.showProgressBar(this);
        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/api/user/ope_video", this);

        req.setParam("video_id", id);
        req.setParam("token", UserHelper.getToken());
        req.setParam("type", isCollect?"1":"2");

        baseActivity.addRequestQueue(req, isCollect?REQUEST_COLLECT:REQUEST_CANCEL_COLLECT, new ReqTag.Builder().handleSimpleRes(true));
    }

    private int currentPos;
    /**
     * 支付
     */
    private void requestPay() {
        baseActivity.showProgressBar(this);
        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/api/user/pay_video"+"?token="+UserHelper.getToken()
                +"&video_id="+videoDatas.get(currentPos).getId()
                +"&anchor_id="+videoDatas.get(currentPos).getMember_id(), this);

        req.setParam("video_id", videoDatas.get(currentPos).getId());
        req.setParam("token", UserHelper.getToken());
        req.setParam("anchor_id", videoDatas.get(currentPos).getMember_id());

        baseActivity.addRequestQueue(req, REQUEST_PAY, new ReqTag.Builder().handleSimpleRes(true));
    }

    @Override
    protected void onResponseSuccess(ReqTag tag, Object data) {
        super.onResponseSuccess(tag, data);
        switch (tag.getReqId()) {
            case REQUEST_DATAS:
                videoDatas.addAll((List<VideoData>)data);
                adapter.notifyDataSetChanged();
                break;
            case REQUEST_COLLECT:
                itemData.setIs_collection("1");
                itemData.setColletion_num(itemData.getColletion_num()+1+"");
                adapter.notifyDataSetChanged();
                break;
            case REQUEST_CANCEL_COLLECT:
                itemData.setIs_collection("0");
                if(itemData.getColletion_num()>0)
                    itemData.setColletion_num(itemData.getColletion_num()-1+"");
                adapter.notifyDataSetChanged();
                break;
            case REQUEST_PAY:
                VideoData vd = videoDatas.get(currentPos);
                vd.setCan_see("1");
                baseActivity.showToast("购买成功");
                view_mask.setVisibility(View.GONE);
                rl_pay.setVisibility(View.GONE);
                startActivity(new Intent(context,PlayVideoActivity.class)
                        .putExtra("title",vd.getUsername())
                        .putExtra("image",vd.getImg())
                        .putExtra("url",vd.getVideo()));
                break;

            default:
                break;
        }
    }

    @Override
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.bt_pay:
                requestPay();
                break;
            case R.id.view_mask:
                view_mask.setVisibility(View.GONE);
                rl_pay.setVisibility(View.GONE);
                break;

            default:
                break;
        }
    }

}
